package com.aat.dxfy.thread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class ThreadPoolUtil {
	public static void main(String[] args) {
		test2();
	}

	public static void test3() {

		ExecutorService es = Executors.newFixedThreadPool(3);
		
		List<Future<Integer>> tasks = new ArrayList<>();
		for (int i = 0; i < 10; i++) {
			final int index = i;

			Callable<Integer> callable = new Callable<Integer>() {
				@Override
				public Integer call() throws Exception {
					System.out.println(index);
					try {
						TimeUnit.SECONDS.sleep(1);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}

					return 1;
				}

			};
			Future<Integer> task = es.submit(callable);
			tasks.add(task);
		}
		for (Future<Integer> future : tasks) {
			try {
				System.out.println("future "+ future.get());
			} catch (InterruptedException | ExecutionException e) {
				e.printStackTrace();
			}
		}
		
		es.shutdown();

	}

	public static void test2() {

		ExecutorService es = Executors.newFixedThreadPool(3);
		for (int i = 0; i < 10; i++) {
			final int index = i;

			es.execute(new Runnable() {
				@Override
				public void run() {
					System.out.println(index);
					try {
						TimeUnit.SECONDS.sleep(1);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			});
		}
		es.shutdown();

	}

	public static void test1() {

		ExecutorService es = Executors.newFixedThreadPool(10);
		for (int i = 0; i < 100; i++) {
			final int index = i;
			es.submit(new Runnable() {
				@Override
				public void run() {
					System.out.println(index);
					try {
						TimeUnit.SECONDS.sleep(1);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			});
		}
		es.shutdown();

	}
}
